package com.nut.lmsc.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.nut.lmsc.common.Result;
import com.nut.lmsc.enums.SmsEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

@Slf4j
@Component
public class SmsUtil {

    //  参数
    private final String ACCESS_KEY_ID = "";
    private final String SECRET = "";
    private final String SYS_DOMAIN = "dysmsapi.aliyuncs.com";
    private final String SIGN_NAME = "";

    private Client client;

    @PostConstruct
    public void init() throws Exception {
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(SECRET);
        // 访问的域名
        config.endpoint = SYS_DOMAIN;
        client = new Client(config);
    }

    /**
     * 发送短信逻辑
     * https://help.aliyun.com/document_detail/419273.html?spm=a2c4g.11186623.0.0.338b5d95Nvs9b9
     * @param mobile
     * @param smsEnum
     * @param params
     * @return
     */
    public Result<String> send(String mobile, SmsEnum smsEnum, Map<String, String> params) {
        String paramJsonStr = JSONUtil.toJsonStr(params);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(mobile)
                .setSignName(SIGN_NAME)
                .setTemplateCode(smsEnum.getTemplateCode())
                .setTemplateParam(paramJsonStr);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            SendSmsResponseBody body = sendSmsResponse.getBody();
            if (ObjectUtil.isNull(body)) {
                log.info("smsSend_body_is_null:{}", JSONUtil.toJsonStr(body));
                return Result.fail("发送body为空");
            }
            if ("OK".equalsIgnoreCase(body.getCode())) {
                return Result.ok(body.getBizId());
            }
            String message = body.getMessage();
            log.error("smsSend_fail, message:{}", message);
            return Result.fail(message);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("smsSend_exception, err_msg:{}", e.getMessage());
            return Result.fail("短信发送异常");
        }
    }

}
